package jgcp.master.service;

import java.util.List;

import jgcp.common.Task;
import jgcp.common.TaskStatus;
import jgcp.common.network.Connection;
import jgcp.common.network.FileSender;
import jgcp.master.management.Worker_Task;
import jgcp.master.network.WorkerList;
import jgcp.message.Message;
import jgcp.message.MessageType;
import jgcp.service.AbstractService;
/**
 * 
 * @Date 31/05/2009
 * @author Jie Zhao (288654)
 * @version 1.0
 */
public class MasterService extends AbstractService {

	public int getNumberOfWorkers() {
		return WorkerList.getInstance().numberOfWorkers();
	}


	public List<Integer> getWorkerList() {
		return WorkerList.getInstance().getWorkerList();
	}

	public void sendMessage(int workerId, Message message) throws Exception {
		WorkerList wl = WorkerList.getInstance();
		Connection c = wl.getConnection(workerId);
		if(c!=null)
		{
//			System.out.println("Sending message:"+message+" To:"+workerId);
			c.writeData(message.toByteArray());
		}
	}


	public void sendMessageToAll(Message msg) {
		List<Integer> wl = WorkerList.getInstance().getWorkerList();
		for(Integer i:wl)
		{
			try {
				sendMessage(i, msg);
			} catch (Exception e) {
			}
		}
	}

	public void sendTask(int workerId, Task task) {
		Message m = new Message();
		m.setType(MessageType.SENDTASK);
		FileSender<Task> ts = new FileSender<Task>(task,task.getFile());
		int port = ts.getPort();
		ts.start();
		m.setMessageBody(""+port);
		try {
			sendMessage(workerId, m);	
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
